package com.hkts.naturalgasauthentication.utils;


import com.hkts.naturalgasauthentication.base.dao.HontDepartmentDao;
import com.hkts.naturalgasauthentication.base.dao.HontPostDao;
import com.hkts.naturalgasauthentication.base.dao.HontUserDao;
import com.hkts.naturalgasauthentication.base.dao.HontUserPostDao;
import com.hkts.naturalgasauthentication.base.entity.HontDepartment;
import com.hkts.naturalgasauthentication.base.entity.HontPost;
import com.hkts.naturalgasauthentication.base.entity.HontUser;
import com.hkts.naturalgasauthentication.base.entity.HontUserPost;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Exrickx
 */
@Component
@Slf4j
public class SecurityUtil {

    @Autowired
    private HontUserDao hontUserDao;
    @Autowired
    private HontPostDao hontPostDao;
    @Autowired
    private HontDepartmentDao hontDepartmentDao;
    @Autowired
    private HontUserPostDao hontUserPostDao;


    public HontUser getCurrUser(){
        UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        HontUser hontUserByUserName = hontUserDao.findByUserName(user.getUsername());
        HontDepartment byDeparId = hontDepartmentDao.findById(hontUserByUserName.getDepartmentId());
        List<HontUserPost> byHontUserPost = hontUserPostDao.findByHontUserId(hontUserByUserName.getId());
        if (byHontUserPost.size() > 0) {
            List<String> postIds = new ArrayList<>();
            for (int i = 0; i < byHontUserPost.size(); i++) {
                HontPost hontPost = hontPostDao.findById(byHontUserPost.get(i).getHontPostId());
                if(hontPost!=null){
                    postIds.add(hontPost.getTitle());
                }
            }
            hontUserByUserName.setPostTile(postIds);
        }
        if(byDeparId!=null){
            hontUserByUserName.setDepartmentTile(byDeparId.getTitle());
        }
        return hontUserByUserName;
    }
}